import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common';
import { Request, Response } from 'express';
import { ErroMessage, ErrorRes } from './ErrorRes';
import { LoggerService } from '../_logger/logger.service';
import { Logger } from 'libs/db/entity/logger.entity';
import { Reflector } from '@nestjs/core';
import { moduleLoggerInfo } from '../_decorator/logger-info';

@Injectable()
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {

  constructor(private readonly _logger: LoggerService) {
  }
  
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    const UserMessage =
      exception instanceof HttpException
        ? exception.message
        : '联系相关技术人员';

    this._logger.error(exception.message, exception.name, exception.stack)
    
    let exceptionRes = <object>exception.getResponse()

    let errorMessage : ErroMessage = <ErroMessage>exception.getResponse()
    
    let errorRes : ErrorRes = {
      ...errorMessage,
      path: request.url,
      timestamp: new Date().toISOString(),
    } 

    response
      .status(status)
      .json(errorRes);
  }
}
